<template>
  <div>
    <!--  面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!--    添加角色区域-->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible=true">添加角色</el-button>
        </el-col>
      </el-row>
      <!--    角色列表区域-->
      <el-table
          :data="roleList"
          border
          stripe
          style="width: 100%">
        <!--      展开列-->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom',i1 === 0?'bdtop':'','vcenter']" v-for="(item1,i1) in scope.row.children"
                    :key="item1.id">
              <!--            一级权限-->
              <el-col :span="5">
                <el-tag @close="removeRightById(scope.row,item1.id)" closable>{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!--            二级和三级权限-->
              <el-col :span="19">
                <!-- 通过for循环渲染二级权限-->
                <el-row :class="[i2 === 0?'':'bdtop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag @close="removeRightById(scope.row,item2.id)" closable type="success">{{
                        item2.authName
                      }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!--三级权限-->
                  <el-col :span="18">
                    <el-tag @close="removeRightById(scope.row,item3.id)" closable v-for="(item3,i3) in item2.children"
                            :key="item3.id" type="warning">{{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>


              </el-col>
            </el-row>
          </template>

        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditRoleForm(scope.row.id)">编辑
            </el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeRole(scope.row.id)">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="showRightsDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--  添加角色对话框-->
    <el-dialog
        title="添加角色"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="handleAddClose"
    >
      <!--     内容主体区域-->
      <el-form :model="addForm"
               :rules="addFormRules"
               ref="addFormRef"
               label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model.trim="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model.trim="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!--    编辑角色对话框-->
    <el-dialog
        title="修改角色"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="handleEditClose"
    >
      <!--     内容主体区域-->
      <el-form :model="editForm"
               :rules="editFormRules"
               ref="editFormRef"
               label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model.trim="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model.trim="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>

    <!--    分配权限对话框-->
    <el-dialog
        title="分配权限"
        :visible.sync="rightsDialogVisible"
        width="50%"
        @close="setRightsDialogClosed"
    >
<!--      树形控件展示区域-->
    <el-tree   ref="treeRef" :default-checked-keys="defKeys" node-key="id" default-expand-all show-checkbox :data="rightsList" :props="treeProps"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setAllRights">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "Roles",
  data() {
    return {
      // 所有角色列表
      roleList: [],
      // 控制添加角色对话框的显示隐藏
      addDialogVisible: false,
      // 添加角色表单的数据
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加角色规则
      addFormRules: {
        roleName: [
          {required: true, message: '请输入角色名称', trigger: 'blur'},
          {min: 3, max: 10, message: '角色名称在 3 到 5 个字符', trigger: 'blur'}
        ],
        roleDesc: [
          {required: true, message: '请输入角色描述', trigger: 'blur'},

        ]
      },
      // 控制修改角色对话框的显示隐藏
      editDialogVisible: false,
      // 修改角色表单,是一个空对象
      editForm: {},
      editFormRules: {
        roleName: [
          {required: true, message: '请输入角色名称', trigger: 'blur'},
          {min: 3, max: 10, message: '角色名称在 3 到 5 个字符', trigger: 'blur'}
        ],
        roleDesc: [
          {required: true, message: '请输入角色描述', trigger: 'blur'},

        ]
      },
      // 控制分配权限对话框的显示隐藏
      rightsDialogVisible: false,
      // 权限列表
      rightsList:[],
      // 树形控件的属性对象
      treeProps:{
        label:'authName',
        children:'children'
      },
      // 默认选中的节点ID值数组
      defKeys:[],
      // 分配角色权限id
      roleId:''
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const {data: res} = await this.$http.get('roles')
      this.roleList = res.data
      console.log(this.roleList)
    },
    // 添加角色表单的重置操作
    handleAddClose() {
      this.$refs.addFormRef.resetFields()
    },
    // 修改角色表单的重置操作
    handleEditClose() {
      this.$refs.editFormRef.resetFields()
    },
    // 添加角色
    async addRole() {
      const {data: res} = await this.$http.post('roles', {
        roleName: this.addForm.roleName,
        roleDesc: this.addForm.roleDesc
      })
      console.log(res)
      if (res.meta.status !== 201) {
        return this.$message.error('添加角色失败')
      }
      this.$message.success('添加角色成功')
      this.getRoleList()
      this.addDialogVisible = false
    },
    // 展示修改角色对话框(根据id查询)
    async showEditRoleForm(roleId) {
      console.log(roleId)
      const {data: res} = await this.$http.get('roles/' + roleId)
      if (res.meta.status !== 200) {
        return this.$message.error('查询角色失败')
      }

      this.editForm = res.data
      console.log('jieguo', this.editForm)
      this.editDialogVisible = true

    },
    // 编辑角色
    editRole() {
      // 对提交表单的预验证
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        // 发送编辑角色的请求
        const {data: res} = await this.$http.put(`roles/${this.editForm.roleId}`, {
          roleName: this.editForm.roleName,
          roleDesc: this.editForm.roleDesc
        })


        if (res.meta.status !== 200) {
          return this.$message.error('修改失败')
        }
        this.editDialogVisible = false
        this.getRoleList()
        this.$message.success('修改成功')

      })
    },
    // 删除角色
    async removeRole(deleteId) {

      const confirmResult = await this.$confirm('确认删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult === 'confirm') {
        const {data: res} = await this.$http.delete('roles/' + deleteId)
        if (res.meta.status !== 200) return this.$message.error('删除角色失败')
        this.$message.success('删除角色成功')
        this.getRoleList()

      }
    },
    // 删除权限
    async removeRightById(role, rightId) {
      // role是角色,rightId是权限id
      // console.log('role',role)
      const confirmResult = await this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消')
      }
      // 发删除角色指定权限的请求
      const {data: res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      }
      // 将角色的children重新赋值
      role.children = res.data

    },
    // 展示分配权限对话框
    async showRightsDialog(role) {
      this.roleId = role.id
      // 获取所有权限列表
      const {data: res} = await this.$http.get('rights/tree')
      if(res.meta.status !==200){
        return this.$message.error('获取权限列表失败')
      }
      this.rightsList = res.data
      console.log('rightList',this.rightsList)
      // 递归获取三级节点id
      this.getLeafKeys(role,this.defKeys)
      this.rightsDialogVisible = true
    },
    // 通过递归的形式,获取角色下所有的三级权限id,并保存到defKeys数组中
    getLeafKeys(node,arr){
      // 如果当前node节点不包含children属性,则是三级节点
      if(!node.children){
          return arr.push(node.id)
      }
      // 如果不是三级节点则要遍历出每一项
      node.children.forEach(item=>{
        this.getLeafKeys(item,arr)
      })
    },
    // 监听分配权限对话框的关闭事件
    setRightsDialogClosed(){
      // 在关闭对话框的时候一定要清空之前的defKeys数组,不然再次点分配权限会自动叠加
      this.defKeys = []
    },
    // 处理分配所有权限
   async setAllRights(){
      // 获取所有的权限key值
      const keys = [
          ...this.$refs.treeRef.getCheckedKeys(),
          ...this.$refs.treeRef.getHalfCheckedKeys()
      ]

      // 把keys数组以,形式拼接成字符串
      const idStr = keys.join(',')

      const {data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{
        rids:idStr
      })

     if(res.meta.status !==200){
       return this.$message.error('分配权限失败')
     }

    this.$message.success('分配权限成功')
     this.getRoleList()
    this.rightsDialogVisible = false



    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 10px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
